/*
 * @Author: fumin 31408026@qq.com
 * @Date: 2025-11-07 15:57:36
 * @LastEditors: fumin 31408026@qq.com
 * @LastEditTime: 2025-11-19 23:54:43
 * @FilePath: /xinjiangkf-miniapp/src/utils/api.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// API请求封装
// const baseURL = 'https://api.example.com' // 替换为实际API地址

/**
 * 获取API基础URL
 * H5开发环境使用代理路径，避免CORS问题
 * 生产环境或非H5环境使用完整URL
 */
const getBaseURL = () => {
    // #ifdef H5
    // H5开发环境：使用代理路径（通过 vite.config.js 中的 proxy 配置）
    // 生产环境：使用完整URL
    // 判断是否为开发环境：通过 location.hostname 或 process.env
    const isDev =
        import.meta.env.DEV ||
        (typeof window !== 'undefined' &&
            (window.location.hostname === 'localhost' ||
                window.location.hostname === '127.0.0.1' ||
                window.location.hostname.includes('192.168.')))

    if (isDev) {
        return '' // 使用相对路径，通过代理转发
    }
    return 'https://kf.xj.189.cn'
        // #endif

    // #ifndef H5
    // 非H5环境（小程序、APP等）：使用完整URL
    return 'https://kf.xj.189.cn'
        // #endif
}

const baseURL = getBaseURL()

/**
 * 判断是否是H5环境
 */
const isH5 = () => {
    // #ifdef H5
    return true
        // #endif
        // #ifndef H5
    return false
        // #endif
}

/**
 * 统一处理请求参数，自动添加wxphone（非H5环境）
 * - 非H5环境：如果用户没有传入wxphone，则自动从存储中获取并添加
 * - H5环境：移除wxphone参数（即使用户传入了也不使用）
 */
const processRequestData = (data) => {
    const processedData = {...data }

    if (isH5()) {
        // H5环境下，移除wxphone参数
        delete processedData.wxphone
    } else {
        // 非H5环境下，如果用户没有传入wxphone，则自动从存储中获取并添加
        if (!processedData.wxphone) {
            const wxphone = uni.getStorageSync('wxphone')
            if (wxphone) {
                processedData.wxphone = wxphone
            }
        }
    }

    return processedData
}

/**
 * 统一处理请求头，H5环境下自动添加openid
 * - H5环境：从存储中获取openid并添加到header
 * - 非H5环境：不添加openid
 */
const processRequestHeader = (optionsHeader = {}) => {
    const header = {
        'Content-Type': 'application/json',
        ...optionsHeader
    }

    // H5环境下，自动添加openid到header
    if (isH5()) {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo && userInfo.openid) {
            header.openid = userInfo.openid
        }
    }

    return header
}

export const request = (options) => {
        return new Promise((resolve, reject) => {
            // 统一处理请求参数
            const processedData = processRequestData(options.data || {})
                // 统一处理请求头
            const processedHeader = processRequestHeader(options.header)

            uni.request({
                url: baseURL + options.url,
                method: options.method || 'GET',
                data: processedData,
                header: processedHeader,
                success: (res) => {
                    console.log('请求成功 = :', res)
                    if (res.statusCode === 200) {
                        resolve(res.data)
                    } else {
                        reject(res)
                    }
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }
    //图形验证码
export const codeRequest = (options) => {
    return new Promise((resolve, reject) => {
        // 统一处理请求参数
        const processedData = processRequestData(options.data || {})
            // 统一处理请求头
        const processedHeader = processRequestHeader(options.header)

        uni.request({
            url: baseURL + options.url,
            method: options.method || 'GET',
            responseType: 'arraybuffer',
            data: processedData,
            header: processedHeader,
            success: (res) => {
                console.log('请求成功 = :', res)
                if (res.statusCode === 200) {
                    resolve(res.data)
                } else {
                    reject(res)
                }
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

// API接口
export const api = {
    // 微信登录相关
    // wxLogin: (data) => request({ url: '/auth/wx-login', method: 'POST', data }),
    // getWxUserInfo: (data) => request({ url: '/auth/wx-user-info', method: 'POST', data }),

    // 微信H5网页授权登录 (snsapi_base)
    wxOAuthLogin: (data) => request({ url: '/xjwechat/wapLogin/getOpenId', method: 'POST', data }),

    // 发送短信验证码
    sendCode: (data) => request({ url: '/xjwechat/miniProgram/sendCode', method: 'POST', data }),
    // 登陆
    login: (data) => request({ url: '/xjwechat/miniProgram/login', method: 'POST', data }),


    // 实时账单查询(实时费用查询-已用话费)
    realTimeBillQuery: (data) => request({ url: '/xjwechat/wxCustomer/realTimeBillQuery', method: 'POST', data }),

    // 费用调整接口
    queryyadjust: (data) => request({ url: '/xjwechat/basicServices/queryyadjust', method: 'POST', data }),

    // 基本服务工单查询
    qryWorkOrder: (data) => request({ url: '/xjwechat/basicServices/qryWorkOrder', method: 'POST', data }),

    //基本服务工单查询
    qryWorkOrderList: (data) => request({ url: '/xjwechat/basicServices/qryWorkOrderList', method: 'POST', data }),

    // // 天翼免密登录相关
    // ctccLogin: (data) => request({ url: '/auth/ctcc-login', method: 'POST', data }),
    // getCtccUserInfo: (data) => request({ url: '/auth/ctcc-user-info', method: 'POST', data }),

    // 用户相关
    // getUserInfo: () => request({ url: '/user/info' }),
    // updateUserInfo: (data) => request({ url: '/user/info', method: 'POST', data }),

    // 账单相关
    getBillList: (data) => request({ url: '/xjwechat/basicServices/payInfo', method: 'POST', data }),
    // getBillDetail: (id) => request({ url: `/bill/${id}` }),

    //查询详单
    getDetailList: (data) => request({ url: '/xjwechat/basicServices/qryDetailList', method: 'POST', data }),

    //充值记录(费用明细变动同一个接口参数不一样)
    getRechargeRecord: (data) => request({ url: '/xjwechat/basicServices/pRecor', method: 'POST', data }),

    // 套餐相关
    // getPackageInfo: () => request({ url: '/package/info' }),

    // 查询套餐余量 首页
    queryUResourc: (data) => request({ url: '/xjwechat/wxCustomer/uResourc', method: 'POST', data }),

    // 查询套餐余量 详情
    queryAllowance: (data) => request({ url: '/xjwechat/basicServices/mealAllowance', method: 'POST', data }),


    //查询用户星级
    queryStartLevelInfo: (data) => request({ url: '/xjwechat/wxCustomer/qryStartLevelInfo', method: 'POST', data }),

    //身份验证
    userIDCheck: (data) => request({ url: '/xjwechat/basicServices/userIDCheck', method: 'POST', data }),

    //发送详单用户发送短信
    sendUserCheckSmsCode: (data) => request({ url: '/xjwechat/basicServices/sendUserCheckSmsCode', method: 'POST', data }),


    //投诉进度查询用户发送短信 入参比sendUserCheckSmsCode 多一个objType， 值为 1投诉编码 2联系电话 3 业务号码   对应 3个tab ）
    sendTsUserCheckSmsCode: (data) => request({ url: '/xjwechat/basicServices/sendTsUserCheckSmsCode', method: 'POST', data }),

    //获取图形验证码
    getImgCheckCode: (params) => codeRequest({ url: '/xjwechat/basicServices/getImgCheckCode/idcheck', data: params }),

    //首页话费余额
    queryBalance: (data) => request({ url: '/xjwechat/wxCustomer/queryBalance', method: 'POST', data }),

    // 余额相关
    // getBalanceDetail: (params) => request({ url: '/balance/detail', data: params }),

    // 紧急开机
    getStartLevel: (data) => request({ url: '/xjwechat/openService/getStartLevel', method: 'POST', data }),

    // 查询绑定号码宽带账号
    queryBroadBand: (data) => request({ url: '/xjwechat/broadband/queryBroadBand', method: 'POST', data }),

    // 校验宽带账号是否存在
    checkUserIsExist: (data) => request({ url: '/xjwechat/broadband/checkUserIsExist', method: 'POST', data }),

    // 验证宽带状态并下工单进行宽带报障(是否欠费，是否有在途单，是否有群障)
    verificationLocalBroadBandReport: (data) => request({ url: '/xjwechat/broadband/verificationLocalBroadBandReport', method: 'POST', data }),

    // 提交宽带工单
    workOrder: (data) => request({ url: '/xjwechat/broadband/workOrder', method: 'POST', data }),

    // 提交手机报障
    phoneWorkOrder: (data) => request({ url: '/xjwechat/broadband/phoneWorkOrder', method: 'POST', data }),


    // 提交手机报障
    wechatAuth: (data) => request({ url: '/xjwechat/wapLogin/wechatAuth', method: 'POST', data }),

    // 提交手机报障
    getOpenId: (code) => request({ url: '/xjwechat/wapLogin/getOpenId?code=' + code, method: 'POST', data: { code } }),


    sendCodeh5: (data) => request({ url: '/xjwechat/bind/sendCode', method: 'POST', data }),

    toBind: (data) => request({ url: '/xjwechat/bind/toBind', method: 'POST', data }),


    // 我要投诉 提交投诉工单
    dxtxworkOrder: (data) => request({ url: '/xjwechat/broadband/dxtxworkOrder', method: 'POST', data }),


    // 手机增值业务查询
    querySpAddedProduct: (data) => request({ url: '/xjwechat/addedProduct/querySpAddedProduct', method: 'POST', data }),

    // 电子发票
    getInvoiceList: (data) => request({ url: '/xjwechat/wxCustomer/getInvoiceList', method: 'POST', data }),
    //开发票
    writeInvoice: (data) => request({ url: '/xjwechat/wxCustomer/writeInvoice', method: 'POST', data }),
    //预览发票
    previewInvoice: (data) => request({ url: '/xjwechat/wxCustomer/previewInvoice', method: 'POST', data }),

    // 详单查询
    // queryDetail: (data) => request({ url: '/detail/query', method: 'POST', data }),

    // 报障
    // submitFault: (data) => request({ url: '/fault/submit', method: 'POST', data }),

    // 增值业务
    // getMobileValueAdded: () => request({ url: '/value-added/mobile' }),
    // getITVValueAdded: () => request({ url: '/value-added/itv' }),

    // 身份验证
    // sendVerifyCode: (phone) => request({ url: '/auth/send-code', method: 'POST', data: { phone } }),
    // verifyIdentity: (data) => request({ url: '/auth/verify', method: 'POST', data })

    // 跳转数字人客服
    getSzrUrl: (userphone) => request({ url: '/xjwechat/wxAuth/getszrurl', method: 'POST', data: { userphone } }),
    // 跳转文字客服
    getH5KFUrl: (userphone) => request({ url: '/xjwechat/wxCustomer/getH5KFUrl', method: 'POST', data: { userphone } }),
}